package com.zj.web.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.zj.config.AlipayConfig;
import com.zj.service.AlipayERService;
import com.zj.service.AlipayService;
import com.zj.service.OrdersService;
import com.zj.web.bean.MyUserDTO;
import com.zj.web.bean.ResponseResult;
import io.swagger.v3.oas.models.responses.ApiResponse;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/auth/alipay")
public class AlipayController {
    @Autowired
    private AlipayService alipayService;
    @Autowired
    private AlipayConfig alipayConfig;
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private AlipayERService alipayERService;
    // 创建支付表单
    @PostMapping("/create")
    public ResponseEntity<ResponseResult> createOrder(@RequestParam("orderId") Long orderId,
                                                      @RequestParam("totalAmount") String totalAmount,
                                                      @RequestParam("email") String email) {
        try {
            // 生成商户订单号（确保唯一性）
            Long outTradeNo = orderId;

            String form = alipayService.createOrder(
                    outTradeNo,
                    totalAmount,
                    email
            );

//            // 保存订单到数据库
//            saveOrder(outTradeNo, orderRequest);

            return ResponseEntity.status(HttpStatus.OK).body(ResponseResult.ok().setdata(form));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(ResponseResult.error("创建订单失败"));
        }
    }

        //异步回调
    @PostMapping("/toSuccess")
    public String handleAlipayNotify(HttpServletRequest request) {
        Map<String, String> params = convertRequestToMap(request);

        try {
            // 验证签名
            boolean signVerified = AlipaySignature.rsaCheckV1(
                    params,
                    alipayConfig.getAlipayPublicKey(),
                    alipayConfig.getCharset(),
                    alipayConfig.getSignType()
            );

            if (!signVerified) {
                throw new RuntimeException("支付宝异步通知签名验证失败");
            }

            // 验证通知数据的正确性
            String appId = params.get("app_id");
            if (!alipayConfig.getAppId().equals(appId)) {
                throw new RuntimeException("app_id不一致");
            }

            // 处理交易状态
            String tradeStatus = params.get("trade_status");
            String outTradeNo = params.get("out_trade_no");
            System.out.println(outTradeNo);

            if ("TRADE_SUCCESS".equals(tradeStatus) ||
                    "TRADE_FINISHED".equals(tradeStatus)) {
                // 更新订单状态为支付成功
                ordersService.updateOrderStatus(Long.valueOf(outTradeNo), 1,null);
                return "redirect:http://localhost:8080/#/send";
            }else {
                return "redirect:http://localhost:8080/#/cart";
            }
        } catch (AlipayApiException e) {
            throw new RuntimeException("支付宝回调处理异常", e);
        }
    }

    private Map<String, String> convertRequestToMap(HttpServletRequest request) {
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();

        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = iter.next();
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }

        return params;
    }

    @GetMapping("/return")
    public String handleAlipayReturn(HttpServletRequest request, Model model) {
        Map<String, String> params = convertRequestToMap(request);

        try {
            // 1. 验证签名（同步返回也需要验证）
            boolean signVerified = AlipaySignature.rsaCheckV1(
                    params,
                    alipayConfig.getAlipayPublicKey(),
                    alipayConfig.getCharset(),
                    alipayConfig.getSignType()
            );

            if (!signVerified) {
                model.addAttribute("error", "签名验证失败");
                return "alipay-error";  // 返回错误页面
            }

            // 2. 获取支付结果参数
            String outTradeNo = params.get("out_trade_no");
            String tradeNo = params.get("trade_no");
            String totalAmount = params.get("total_amount");

            // 3. 将数据传递给页面显示
            model.addAttribute("outTradeNo", outTradeNo);
            model.addAttribute("tradeNo", tradeNo);
            model.addAttribute("totalAmount", totalAmount);

            // 4. 返回成功页面
            return "alipay-success";
        } catch (AlipayApiException e) {
            model.addAttribute("error", "处理支付返回结果时发生错误");
            return "alipay-error";
        }
    }


    // 创建二维码支付订单
    @PostMapping("/createQRCode")
    public ResponseEntity<ResponseResult> createQRCodeOrder(@RequestParam("orderId") Long orderId,
                                                            @RequestParam("totalAmount") String totalAmount,
                                                            @RequestParam("email") String email) {
        try {
            String qrCode = alipayERService.createQRCodeOrder(orderId, totalAmount, email);
            return ResponseEntity.ok(ResponseResult.ok().setdata(qrCode));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ResponseResult.error("创建二维码订单失败: " + e.getMessage()));
        }
    }

    // 查询支付状态
    @GetMapping("/queryStatus/{orderId}")
    public ResponseEntity<ResponseResult> queryOrderStatus(@PathVariable("orderId") Long orderId) {
        try {
            String status = alipayERService.queryOrderStatus(orderId);
            return ResponseEntity.ok(ResponseResult.ok().setdata(status));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ResponseResult.error("查询订单状态失败"));
        }
    }
}
